﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.Text;
using System.Xml.Linq;
using System.Collections.Specialized;
using HtmlAgilityPack;
using Guline.Iuh.TichLuy.Models;
namespace Guline.Iuh.TichLuy.Controllers
{
    public class HomeController : Controller
    {
        private WebClient wc;
        
        public ActionResult DeleteCookie()
        {
            Session["xsession"] = null;
            return RedirectToAction("Index");
        }
        public ActionResult ViewNew()
        {
            /*if (Request.Browser.IsMobileDevice)
            {
                return View("IndexMobile");
            }
            else {
                return View();
            }*/
            return View();

        }
        [HttpPost]
        public ActionResult ViewNew(Models.SinhVien model)
        {
            if (ModelState.IsValid)
            {
                if (Session["xWebclient"] != null)
                {
                    wc = (WebClient)Session["xWebclient"];
                }
                else
                {
                    wc = new WebClient();
                    wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
                    wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    wc.Headers.Add("Accept-Encoding", "identity");
                    wc.Headers.Add("Accept-Language", "en-US,en;q=0.8");
                    wc.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
                    wc.Headers.Add("ContentType", "application/x-www-form-urlencoded");
                }
                NameValueCollection postData = new NameValueCollection() 
               { 
                      { "txtMaSV", model.MaSV },  //order: {"parameter name", "parameter value"}
                      { "txtMaXacNhan", model.MaBV.ToUpper() }
               };
                try
                {
                    string pagesource = Encoding.UTF8.GetString(wc.UploadValues("http://iuh.edu.vn/ketquahoctap/Default.aspx", postData));

                    HtmlDocument xdoc = new HtmlDocument();
                    xdoc.LoadHtml(pagesource);
                    var divresult = xdoc.DocumentNode.SelectSingleNode("//div[@id='MainContent_divKetQua']");
                    string txt = divresult.InnerHtml;
                    if (divresult.InnerText.Length > 0 && txt != "\r\n    \r\n    ")
                    {
                        Models.XdocSession xsession = new Models.XdocSession();
                        xsession.xdoc = xdoc;
                        xsession.MaSV = model.MaSV;
                        Session["xsession"] = xsession;
                        return RedirectToAction("Result");
                    }
                    else
                    {

                        ModelState.AddModelError("NotOk", "Mã sinh viên hoặc mã xác nhận không đúng");
                    }
                }
                catch
                {
                    ModelState.AddModelError("NotOk", "Đã có lỗi xảy ra.");
                }
            }
            return View(model);
        }
        public ActionResult Index()
        {
            /*if (Request.Browser.IsMobileDevice)
            {
                return View("IndexMobile");
            }
            else {
                return View();
            }*/
            return View();
            
        }
        [HttpPost]
        public ActionResult Index(Models.SinhVien model)
        {
            if (ModelState.IsValid)
            {
                if (Session["xWebclient"] != null)
                {
                    wc = (WebClient)Session["xWebclient"];
                }
                else
                {
                    wc = new WebClient();
                    wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
                    wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    wc.Headers.Add("Accept-Encoding", "identity");
                    wc.Headers.Add("Accept-Language", "en-US,en;q=0.8");
                    wc.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
                    wc.Headers.Add("ContentType", "application/x-www-form-urlencoded");
                }
                NameValueCollection postData = new NameValueCollection() 
               { 
                      { "txtMaSV", model.MaSV },  //order: {"parameter name", "parameter value"}
                      { "txtMaXacNhan", model.MaBV.ToUpper() }
               }; 
                try
                {
                string pagesource = Encoding.UTF8.GetString(wc.UploadValues("http://iuh.edu.vn/ketquahoctap/Default.aspx", postData));
                
                    HtmlDocument xdoc = new HtmlDocument();
                    xdoc.LoadHtml(pagesource);
                    var divresult = xdoc.DocumentNode.SelectSingleNode("//div[@id='MainContent_divKetQua']");
                    string txt = divresult.InnerHtml;
                    if (divresult.InnerText.Length > 0 && txt != "\r\n    \r\n    ")
                    {
                        Models.XdocSession xsession = new Models.XdocSession();
                        xsession.xdoc = xdoc;
                        xsession.MaSV = model.MaSV;
                        Session["xsession"] = xsession;
                        return RedirectToAction("Result");
                    }
                    else
                    {
                       
                        ModelState.AddModelError("NotOk", "Mã sinh viên hoặc mã xác nhận không đúng");
                    }
                }
                catch
                {
                    ModelState.AddModelError("NotOk", "Đã có lỗi xảy ra.");
                }
            }
            return View(model);
        }
        public ActionResult Result() {
            if (Session["xsession"] == null)
                return RedirectToAction("Index");
            else
            {
                XdocSession xdoc = (XdocSession)Session["xsession"];
                
                Excute.Calculator cal = new Excute.Calculator(xdoc.xdoc,xdoc.MaSV);
                try
                {
                    cal.buildtichluy();
                }
                catch
                { 

                }
                return View(cal);
            }
            
        }
        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View("AboutMobile");
        }
        public ActionResult Captcha()
        {
            if (Session["xWebclient"] != null)
            {
                wc = (WebClient)Session["xWebclient"];
            }
            else
            {
                wc = new WebClient();
                wc.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5");
                wc.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                wc.Headers.Add("Accept-Encoding", "identity");
                wc.Headers.Add("Accept-Language", "en-US,en;q=0.8");
                wc.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
                wc.Headers.Add("ContentType", "application/x-www-form-urlencoded");
                Session["xWebclient"] = wc;
            }
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://iuh.edu.vn/ketquahoctap/Default.aspx");
            request.CookieContainer = new
                 CookieContainer();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Cookie[] arr_cook = new
 Cookie[response.Cookies.Count];
            response.Cookies.CopyTo(arr_cook, 0);
            string
 str_cookie = ""
;
            for
 (int
 i = 0; i < arr_cook.Length; i++)
            {
                str_cookie += arr_cook[i].ToString() + ";"
;
            }

            wc.Headers.Add("Cookie"
, str_cookie);

            return File(wc.DownloadData("http://iuh.edu.vn/ketquahoctap/ConfirmImage.aspx"), "image/gif");
        }
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View("MobileContact");
        }
        [HttpPost]
        public ActionResult Contact(Models.ContactView model)
        {
            if(ModelState.IsValid)
            {
                bool result = Utils.SMTPSendMail.SendMail(model.EmailOrFBName, model.Title, model.Content +"<br>"+ model.FullName);
                if (result)
                {
                    ModelState.AddModelError("","Cám ơn bạn đã gửi yêu cầu, chúng tôi sẽ xử lý và phản hồi lại sớm nhất.");
                }
                else
                {
                    ModelState.AddModelError("", "Có lỗi xảy ra, bạn vui lòng thử lại.");
                }
            }
            return View();
        }
        public ActionResult Mobile()
        {
            return View();
        }
    }
}
